import RNFS from 'react-native-fs';
import {Dirs, FileSystem} from 'react-native-file-access';
import dayjs from 'dayjs';
import {fileTypeFromFile} from 'file-type';
import RNFileType from 'react-native-file-type';
import sortArray from 'sort-array';
import {round} from 'lodash';

export default async ({targetPath = ''}) => {
  let total = 0;
  let size = 0;
  let totalSonDir = 0;
  let totalSonFile = 0;
  return new Promise(async (resolve, reject) => {
    const lastDirPath = 'last-dir-' + dayjs().format('YYYYMMDDHHmmssSSS');
    let oneAllFiles = await FileSystem.statDir(targetPath);
    oneAllFiles.push({
      path: lastDirPath,
      type: 'directory',
    });
    const oneSonDirs = oneAllFiles.filter(item => item.type === 'directory');
    const oneSonFiles = oneAllFiles.filter(item => item.type !== 'directory');
    oneSonFiles.forEach(item => {
      total++;
      size += item.size;
    });

    totalSonDir = oneSonDirs.length - 1;
    totalSonFile = oneSonFiles.length;

    const fun = async ({list = []}) => {
      for (const nowItem of new Set(list)) {
        if (nowItem.path === lastDirPath) {
          resolve({
            path: targetPath,
            total,
            size,
            sizeKB: round(size / 1024, 2),
            sizeMB: round(size / 1024 / 1024, 2),
            sizeGB: round(size / 1024 / 1024 / 1024, 2),
            totalSonDir,
            totalSonFile,
          });
        } else {
          const allFiles = await FileSystem.statDir(nowItem.path);
          const sonDirs = allFiles.filter(item => item.type === 'directory');
          const sonFiles = allFiles.filter(item => item.type !== 'directory');

          sonFiles.forEach(item => {
            total++;
            size += item.size;
          });
          if (sonDirs.length > 0) {
            await fun({list: sonDirs});
          }
        }
      }
    };
    fun({list: oneSonDirs});
  });
};
